package com.example.campuslink.ui.activity.ai

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.http.ImageRequest
import com.example.campuslink.commen.http.ImageSaver
import com.example.campuslink.commen.http.Retrofit
import com.example.campuslink.commen.tools.AnimalMap
import com.example.campuslink.databinding.ActivityImageProduceBinding
import com.example.campuslink.ui.activity.BaseActivity
import com.example.campuslink.viewModel.ai.InquiriesViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ImageProduceActivity : BaseActivity<ActivityImageProduceBinding, InquiriesViewModel>(
    InquiriesViewModel::class.java,
    R.layout.activity_image_produce,
    BR.viewModel
) {
    private val options: MutableList<String> = mutableListOf()
    private var map: Map<String, String?>? = null
    private var imgPixel = ""
    private lateinit var adapter: ArrayAdapter<String>
    private var imageUrl = ""

    fun onClick() {
        mViewDataBinding?.spinnerShowImgSize?.setOnItemSelectedListener(object :
            AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                imgPixel = options[p2]
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {

            }
        })
        mViewDataBinding?.etIntroduceContent?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入内容并发送请求
                val question = mViewDataBinding?.etIntroduceContent?.text.toString()
                if (question.isNotBlank()) {
                    generateImage(question, imgPixel)
                }
                true // 表示已处理该事件
            } else {
                false // 未处理其他动作
            }
        }
        mViewDataBinding?.btnKeepPhoto?.setOnClickListener({
            lifecycleScope.launch {
                if(imageUrl!=""){
                    ImageSaver.saveImageToGallery(this@ImageProduceActivity, imageUrl)
                }else{
                    lifecycleScope.launch(Dispatchers.Main) {
                        Toast.makeText(this@ImageProduceActivity, "还未生成图片,保存失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }

    override fun initView() {
        initData()

        onClick()
        mViewDataBinding?.spinnerShowImgSize?.adapter = adapter

    }


    private fun generateImage(content: String, imgPixel: String) {
        mViewDataBinding?.progressLoad?.visibility = View.VISIBLE

        val processedContent = if (map.isNullOrEmpty()) {
            content
        } else {
            // 1. 精确匹配
            map!![content]
                ?: run {
                    // 2. 部分匹配
                    map?.keys?.firstOrNull { content.contains(it) }?.let { key ->
                        map!![key]
                    } ?: content // 保持原内容如果都没匹配到
                }
        }

        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val request = ImageRequest(
                    batch_size = 1,
                    image_size = imgPixel,
                    model = "stabilityai/stable-diffusion-xl-base-1.0",
                    prompt = processedContent
                )

                val response = Retrofit.instance.generateImage(
                    request = request
                )

                withContext(Dispatchers.Main) {
                    mViewDataBinding?.progressLoad?.visibility = View.GONE

                    if (response.isSuccessful) {
                        response.body()?.images?.firstOrNull()?.url?.let { url ->
                            imageUrl = url
                            Glide.with(this@ImageProduceActivity)
                                .load(url)
                                .into(mViewDataBinding?.ivCreateImg!!)
                        } ?: showErrorImage()
                    } else {
                        showErrorImage()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    mViewModel?.handleError(e)
                    mViewDataBinding?.progressLoad?.visibility = View.GONE
                    showErrorImage()
                }
            }
        }
    }

    private fun showErrorImage() {
        Glide.with(this)
            .load(R.drawable.ic_empty)
            .into(mViewDataBinding?.ivCreateImg!!)
    }

    private fun initData() {
        options.add("1024x1024")
        options.add("960x1280")
        options.add("768x1024")
        options.add("720x1440")
        options.add("720x1280")
        map = AnimalMap().ChangeAniName()
        imgPixel = options[0]
        adapter = ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, options
        )
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item)
    }
}